﻿Imports System.Drawing

Public Class MoveHandle
    Private sp As Point
    Private M_Center As Point
    Public Event Moved(ByVal OldPoint As Point, ByVal NewPoint As Point)
    Public Event Remove(ByVal sender As Object)
    Public Property Center() As Point
        Get
            Return M_Center
        End Get
        Set(ByVal value As Point)
            M_Center = value
            Me.Left = M_Center.X - 10
            Me.Top = M_Center.Y - 10
        End Set
    End Property
    Public Sub Pop()
        Me.Visible = True
    End Sub
    Private Sub MoveHandle_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        sp = Windows.Forms.Control.MousePosition
    End Sub

    Private Sub MoveHandle_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
        If e.Button = Windows.Forms.MouseButtons.Left Then
            Dim P As Drawing.Point
            Dim NP As Drawing.Point
            NP.X = Me.Left + (Me.Width / 2)
            NP.Y = Me.Top + (Me.Height / 2)

            P = Windows.Forms.Control.MousePosition

            Dim X As Integer
            Dim Y As Integer

            X = P.X - sp.X
            Y = P.Y - sp.Y
            If Math.Abs(X) > 5 Or Math.Abs(Y) > 5 Then
                Me.Left = Me.Left + X
                Me.Top = Me.Top + Y

                Dim V As Integer = (Me.Top / 5)
                Me.Top = V * 5

                V = (Me.Left / 5)
                Me.Left = V * 5

                If Me.Left < 0 Then Me.Left = 0
                If Me.Right > Parent.Width Then Me.Left = Parent.Width - Me.Width
                If Me.Top < 0 Then Me.Top = 0
                If Me.Bottom > Parent.Height Then Me.Top = Parent.Height - Me.Height
                Dim Old As Point = M_Center
                M_Center.X = Me.Left + 10
                M_Center.Y = Me.Top + 10
                RaiseEvent Moved(Old, M_Center)
                sp = P
            End If
        End If

    End Sub

    Private Sub MoveHandle_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        Me.Width = 20
        Me.Height = 20
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Visible = False
    End Sub

    Private Sub RemoveMe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveMe.Click
        RaiseEvent Remove(Me)
    End Sub

End Class
